import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:namewava/pages/mine/widgets/jc_pop.dart';
import 'package:namewava/utils/jc_cache.dart';
import 'package:namewava/utils/jc_global.dart';
import 'package:namewava/utils/jc_image_path.dart';
import 'package:namewava/utils/jc_picker.dart';
import 'package:namewava/utils/jc_screenutil_info.dart';
import 'package:namewava/utils/jc_text_style.dart';
import 'package:namewava/utils/js_request.dart';
import 'package:notification_centre/notification_centre.dart';
import 'package:permission_handler/permission_handler.dart';

class JcMineInfo extends StatefulWidget {
  const JcMineInfo({super.key});

  @override
  State<JcMineInfo> createState() => _JcMineInfoState();
}

class _JcMineInfoState extends State<JcMineInfo> {
  RxString userAvater = ''.obs;
  RxString nickname = ''.obs;
  RxString borthday = ''.obs;
  RxString country = ''.obs;
  List countrys = [
    'Zimbabwe',
    'Zambia',
    'South Africa',
    'Mayotte',
    'Yemen',
    'Samoa',
    'Wallis and Futuna',
    'Vanuatu',
    'Vietnam',
    'Venezuela',
    'Vatican City',
    'Uzbekistan',
    'Uruguay',
    'USA',
    'Ukraine',
    'Uganda',
    'Tanzania',
    'Tuvalu',
    'Turkey',
    'Tonga',
    'Tunisia',
    'Turkmenistan',
    'Timor-Leste',
    'Tokelau',
    'Tajikistan',
    'Thailand',
    'Togo',
    'Chad',
    'Swaziland',
    'Syria',
    'South Sudan',
    'Suriname',
    'Somalia',
    'Senegal',
    'San Marino',
    'Sierra Leone',
    '	Slovakia',
    'Slovenia',
    'Singapore',
    'Sweden',
    'Sudan',
    'Seychelles',
    'Solomon Islands',
    '	Saudi Arabia',
    'Rwanda',
    '	Russian Federation',
    'Serbia',
    'Romania',
    'Réunion',
    'Qatar',
    'Paraguay',
    'Palau',
    'Portugal',
    'Palestinian territories',
    '	Puerto Rico',
    'Pitcairn Islands',
    'Poland',
    'Pakistan',
    'Papua New Guinea',
    'French polynesia',
    'Peru',
    'Panama',
    'Oman',
    'New Zealand',
    'Niue',
    'Nauru',
    'Nepal',
    'Norway',
    'Netherlands',
    'Nicaragua',
    'Nigeria',
    '	Norfolk Island',
    'Niger',
    'New Caledonia',
    'Namibia',
    'Mozambique',
    'Malaysia',
    'Mexico',
    'Malawi',
    'Maldives',
    'Mauritius',
    'Malta',
    'Montserrat',
    'Mauritania',
    'Martinique',
    '	Northern Mariana Islands',
    'Macao',
    'Mongolia',
    'Myanmar',
    'Mali',
    'Madagascar',
    'Montenegro',
    'Moldova',
    'Monaco',
    'Morocco',
    'Libya',
    'Latvia',
    'Luxembourg',
    'Lithuania',
    'Lesotho',
    'Liberia',
    'Sri Lanka',
    'Liechtenstein',
    'St. Lucia',
    'Lebanon',
    'Laos',
    'Kazakhstan',
    'Cayman Islands',
    'Kuwait',
    'South Korea',
    'North Korea',
    'The Comoros',
    'Kiribati',
    'Cambodia',
    'Kyrgyzstan',
    'Kenya',
    'Japan',
    'Jordan',
    'Jamaica',
    'Jersey',
    'Italy',
    'Iceland',
    'Iran',
    'Iraq',
    'British Indian Ocean Territory',
    'India',
    'Isle of Man',
    'Israel',
    'Ireland',
    'Indonesia',
    'Hungary',
    'Haiti',
    'Croatia',
    'Honduras',
    'Heard Island and McDonald Islands',
    'Hong Kong',
    'Guyana',
    'Guinea-Bissau',
    'Guam',
    'Guatemala',
    'South Georgia and the South Sandwich Islands',
    'Greece',
    'Equatorial Guinea',
    'Guadeloupe',
    'Guinea',
    'Gambia',
    'Greenland',
    'Gibraltar',
    'Ghana',
    'Guernsey',
    'French Guiana',
    'Georgia',
    'Grenada',
    '	Great Britain',
    'Gabon',
    'France',
    'Faroe Islands',
    'Federated States of Micronesia',
    'Falkland Islands',
    'Fiji',
    'Finland',
    'Ethiopia',
    'Spain',
    'Eritrea',
    'Western Sahara',
    'Egypt',
    'Estonia',
    'Ecuador',
    'Algeria',
    'Dominican Republic',
    'Dominica',
    'Denmark',
    'Djibouti',
    'Germany',
    'Czech Republic',
    'Cyprus',
    'Christmas Island',
    '	Cape Verde',
    'Cuba',
    'Costa Rica',
    'Colombia',
    'Cameroon',
    'Chile',
    'Cook Islands',
    'Switzerland',
    'Canada',
    'Belize',
    'Belarus',
    'Botswana',
    'Bouvet Island',
    'Bhutan',
    'The Bahamas',
    'Brazil',
    'Caribbean Netherlands',
    'Bolivia',
    'Brunei',
    'Bermuda',
    'Saint Barthélemy',
    'Benin',
    'Burundi',
    'Bahrain',
    'Bulgaria',
    'Burkina',
    'Belgium',
    'Bangladesh',
    'Barbados',
    'Azerbaijan',
    'Aruba',
    'Australia',
    'Austria',
    '	American Samoa',
    'Argentina',
    'Antarctica',
    'Angola',
    'Armenia',
    'Albania',
    'Anguilla',
    'Afghanistan',
    'United Arab Emirates',
    'Andorra',
  ];
  _wavaUserInfo() {
    JsRequest.getWavaUserInfo(success: (res) {
      var isFirstRegister = JcCache.getInstance().get('isFirstRegister');
      if (isFirstRegister is bool && isFirstRegister) {
        userAvater.value = '';
      } else {
        userAvater.value = res['avatarThumbUrl'];
      }

      nickname.value = res['nickname'];
      borthday.value = res['birthday'];
      country.value = res['country'];
    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _wavaUserInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: GestureDetector(
      child: Container(
        height: JcScreenutilInfo.screenHeight,
        decoration: const BoxDecoration(
            image: DecorationImage(
                image: AssetImage(JcImagePath.jcMineBg), fit: BoxFit.fill)),
        child: SingleChildScrollView(
          child: Column(
            children: [
              _topWidget(),
              _nameWidget(),
              _brithdayWdiget(),
              _cWdiget(),
              SizedBox(
                height: 70.h,
              ),
              GestureDetector(
                child: Container(
                  margin: EdgeInsets.only(left: 52.w, right: 52.w),
                  height: 53.h,
                  alignment: Alignment.center,
                  decoration: const BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage(JcImagePath.jcMineItemBg),
                          fit: BoxFit.fill)),
                  child: Text(
                    'Submit',
                    style: JcTextStyle.sourceKeynoteartHansTextStyle(
                        16.sp, Colors.white),
                  ),
                ),
                onTap: () {
                  _saveUserInfo();
                },
              )
            ],
          ),
        ),
      ),
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
    ));
  }

  _topWidget() {
    return Container(
      margin: EdgeInsets.only(
          top: JcScreenutilInfo.statusBarHeight + 10.h,
          left: 36.w,
          right: 36.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            width: 36.w,
            height: 145.w,
            padding: EdgeInsets.only(top: 10.h),
            alignment: Alignment.topLeft,
            child: GestureDetector(
              child: Image.asset(
                JcImagePath.jcBackIcon,
                width: 36.w,
                height: 36.w,
              ),
              onTap: () {
                Get.back();
              },
            ),
          ),
          Stack(
            children: [
              GestureDetector(
                child: Container(
                  height: 145.w,
                  width: 145.w,
                  alignment: Alignment.center,
                  decoration: const BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage(JcImagePath.jcMineHeadBg),
                          fit: BoxFit.fill)),
                  child: Container(
                      height: 100.w,
                      width: 100.w,
                      decoration: BoxDecoration(
                          // color: Colors.red,
                          borderRadius: BorderRadius.circular(50.w)),
                      child: Obx(() {
                        return userAvater.value == ''
                            ? ClipRRect(
                                borderRadius: BorderRadius.circular(50.w),
                                child: Image.asset(
                                  JcImagePath.jcWavaDfuHeadIcon,
                                  width: double.infinity,
                                  height: double.infinity,
                                ),
                              )
                            : ClipRRect(
                                borderRadius: BorderRadius.circular(50.w),
                                child: FadeInImage.assetNetwork(
                                    placeholder: JcImagePath.jcWavaDfuHeadIcon,
                                    image: userAvater.value),
                              );
                      })),
                ),
                onTap: () {
                  Get.dialog(
                      JcPop(
                          btnTitles: const ['Camera', 'Album'],
                          cancelTitle: 'Cancel',
                          tapEvents: (index) {
                            print(index);
                            _chooesePhoto(index);
                          }),
                      useSafeArea: false);
                },
              ),
              Positioned(
                  bottom: 10.w,
                  right: 30.w,
                  child: GestureDetector(
                    child: Image.asset(
                      JcImagePath.jcWavaCarme,
                      width: 32.w,
                      height: 32.w,
                    ),
                    onTap: () {
                      Get.dialog(
                          JcPop(
                              btnTitles: const ['Camera', 'Album'],
                              cancelTitle: 'Cancel',
                              tapEvents: (index) {
                                print(index);
                                _chooesePhoto(index);
                              }),
                          useSafeArea: false);
                    },
                  ))
            ],
          ),
          SizedBox(
            width: 36.w,
          )
        ],
      ),
    );
  }

  _nameWidget() {
    return Container(
      margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 60.h),
      height: 46.h,
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      decoration: BoxDecoration(
          color: const Color(0xFFF9F9F9),
          borderRadius: BorderRadius.circular(15.r)),
      child: Row(
        children: [
          Text(
            'Nick Name',
            style: JcTextStyle.octoberDevanagariRegularTextStyle(
                12.sp, const Color.fromRGBO(0, 0, 0, 0.3)),
          ),
          Expanded(child: SizedBox(
            child: Obx(() {
              return TextField(
                textAlign: TextAlign.end,

                textInputAction: TextInputAction.done,
                controller: TextEditingController(text: nickname.value),
                // maxLength: 10,
                style: JcTextStyle.octoberDevanagariRegularTextStyle(
                    14.sp, const Color(0xFF404040)),
                decoration: InputDecoration(
                    hintText: 'Nick Name',
                    contentPadding: EdgeInsets.zero,
                    border:
                        const OutlineInputBorder(borderSide: BorderSide.none),
                    hintStyle: JcTextStyle.octoberDevanagariRegularTextStyle(
                        14.sp, const Color.fromRGBO(181, 181, 181, 1))),
                onChanged: (v) {
                  nickname.value = v;
                },
                onSubmitted: (v) {
                  nickname.value = v;
                },
              );
            }),
          ))
        ],
      ),
    );
  }

  _brithdayWdiget() {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 25.h),
        height: 46.h,
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        decoration: BoxDecoration(
            color: const Color(0xFFF9F9F9),
            borderRadius: BorderRadius.circular(15.r)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              'Date of Birth',
              style: JcTextStyle.octoberDevanagariRegularTextStyle(
                  12.sp, const Color.fromRGBO(0, 0, 0, 0.3)),
            ),
            Obx(() {
              return Text(
                borthday.value,
                style: JcTextStyle.octoberDevanagariRegularTextStyle(
                    12.sp, const Color(0xFF404040)),
              );
            }),
          ],
        ),
      ),
      onTap: () {
        JcPicker.showDatePicker(
          context,
          title: 'Choose Birthday',
          clickCallBack: (selectValue, selectIndexArr) {
            print(selectValue);
            String select = selectValue.toString();
            String tmp = select.substring(0, 10);
            final birthdayDate = DateTime.parse(tmp);
            final nowDate = DateTime.now();

            final diffDays = nowDate.difference(birthdayDate).inDays;

            final diffYears = (nowDate.year - birthdayDate.year);
            //  final int completeYears = (diffDays / 365).floor();
            if (diffYears < 18) {
              EasyLoading.showError('Sorry, we only accept age range 18+. please select again.');
            } else {
              borthday.value = tmp;
            }
          },
        );
      },
    );
  }

  _cWdiget() {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 25.h),
        height: 46.h,
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        decoration: BoxDecoration(
            color: const Color(0xFFF9F9F9),
            borderRadius: BorderRadius.circular(15.r)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              'Country',
              style: JcTextStyle.octoberDevanagariRegularTextStyle(
                  12.sp, const Color.fromRGBO(0, 0, 0, 0.3)),
            ),
            Obx(() {
              return Text(
                country.value,
                style: JcTextStyle.octoberDevanagariRegularTextStyle(
                    12.sp, const Color(0xFF404040)),
              );
            }),
          ],
        ),
      ),
      onTap: () {
        JcPicker.showStringPicker(
          context,
          data: countrys,
          title: 'Choose Country',
          clickCallBack: (selectValue, selectIndexArr) {
            print(selectValue);
            country.value = selectValue;
          },
        );
      },
    );
  }

  _saveUserInfo() {
    if (nickname.value == '') {
      EasyLoading.showError('Enter nickname');
      return;
    }

    JsRequest.fixUserInfoRequest(
        parms: {
          'birthday': borthday.value,
          'nickname': nickname.value,
          'country': country.value
        },
        success: (res) {
          NotificationCenter().postNotification('wavaFixUserInfo');
          EasyLoading.showSuccess('Fix Success');
          Get.back();
        });
  }

  _chooesePhoto(int type) async {
    bool permissionResult = await requestPermission(type);
    if (permissionResult) {
      if (mounted) {
        JcGlobal.of(context).logReport({'page': 'editavatar'});
      }
      JsRequest.getUpfileParms(success: (res) {
        _chooeseUserFixImage(type, res);
      });
    } else {
      EasyLoading.showError(type == 0
          ? 'Your camera permission has been denied.'
          : 'Your album permission has been denied.');
    }
  }

  _chooeseUserFixImage(int type, Map oss) async {
    if (type == 0) {
      final pickedFild =
          await ImagePicker().pickImage(source: ImageSource.camera);
      if (pickedFild != null) {
        JsRequest.fixUserAvatarRequest(
            file: pickedFild,
            oss: oss,
            success: (res) {
              String thumbUrl = res['thumbUrl'];
              userAvater.value = thumbUrl;
              JcCache.getInstance().setData('isFirstRegister', false);
              NotificationCenter().postNotification('wavaFixUserAvatar',
                  data: {'url': thumbUrl});
              EasyLoading.showSuccess('Fix Success');
              // Get.back();
            });
        // File file = await MGImageCompressUtil.imageCompressAndGetFile(pickedFild);
        // _handFile(file);
      }
    } else {
      final pickedFild =
          await ImagePicker().pickImage(source: ImageSource.gallery);
      if (pickedFild != null) {
        JsRequest.fixUserAvatarRequest(
            file: pickedFild,
            oss: oss,
            success: (res) {
              String thumbUrl = res['thumbUrl'];
              userAvater.value = thumbUrl;
              JcCache.getInstance().setData('isFirstRegister', false);
              NotificationCenter().postNotification('wavaFixUserAvatar',
                  data: {'url': thumbUrl});
              EasyLoading.showSuccess('Fix Success');
              // Get.back();
            });
        // File file = await MGImageCompressUtil.imageCompressAndGetFile(pickedFild);
        // _handFile(file);
      }
    }
  }

  ////获取权限0相机 1相册
  Future<bool> requestPermission(int type) async {
    var status = type == 0
        ? await Permission.camera.status
        : await Permission.photos.status;

    if (type == 0) {
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        status = await Permission.camera.request();

        if (status == PermissionStatus.granted) {
          return true;
        } else {
          return false;
        }
      }
    } else {
      if (status == PermissionStatus.granted ||
          status == PermissionStatus.limited) {
        return true;
      } else {
        status = await Permission.camera.request();

        if (status == PermissionStatus.granted ||
            status == PermissionStatus.limited) {
          return true;
        } else {
          return false;
        }
      }
    }
  }
}
